from flask import Flask, render_template, redirect, url_for
from flask_login import LoginManager, logout_user, \
    login_required, UserMixin, login_user, current_user
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

from forms import LoginForm, RegistrationForm

app = Flask(__name__)
app.config['SECRET_KEY'] = 'dqefeqwfwe'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:000000@localhost/demo'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    uesrname = db.Column(db.String(16), unique=True, nullable=False)
    password = db.Column(db.String(16), unique=False, nullable=False)
    display_name = db.Column(db.String(16), unique=False, nullable=False)

    def __repr__(self):
        return f'<User {self.uesrname}>'


class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(16), unique=True, nullable=False)
    price = db.Column(db.Integer, unique=False, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    users = db.relationship('User', backref='books')

    def __repr__(self):
        return f'<User {self.name}>'


# python
# Book.users  # 通过书籍获取用户信息
# User.books # 通过用户获取书籍信息

Migrate(app, db)

login_manager = LoginManager(app)
login_manager.login_view = 'login'  # 指定没有登录跳转的页面


@login_manager.user_loader
def load_user(user_id):  # 登录的时候自动记录id
    user = User.query.get(user_id)
    if user:
        user_mix = UserMixin()
        user_mix.id = user.id

        return user_mix


@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        # 保存数据库
        user = User(uesrname=form.uesrname.data,
                    password=form.password.data,
                    display_name=form.display_name.data)  # 创建user对象
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('login'))

    return render_template('register.html', form=form)


@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        # 保存数据库
        uesrname = form.uesrname.data
        password = form.password.data
        users = User.query.filter_by(uesrname=uesrname)
        if users:
            user = users.first()
            if user.password == password:
                user_mix = UserMixin()
                user_mix.id = user.id
                login_user(user_mix)

                return redirect(url_for('index'))

    return render_template('login.html', form=form)


@app.route('/')
@login_required
def index():
    user = User.query.get(current_user.id)
    books = user.books

    book = Book.query.get(1)
    user = book.users
    return render_template('index.html', books=books, user=user)


@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))


if __name__ == '__main__':
    app.run(debug=True)
'''

'''